/**
 * 
 */
package segmentation.border_follow;

import util.ColorTransformer;
import image.Image;

/**
 * @author nquangtrung
 *
 */
public class LuminanceChannelEdgeFollower extends EdgeFollower {

	public LuminanceChannelEdgeFollower(Image image) {
		super(image);
	}

	protected int[][] get3by3(int x, int y) {
		int[][] map = new int[3][3];
		Image img = this.getImage();
		
		for (int dx = -1; dx <= 1; dx++) {
			for (int dy = -1; dy <= 1; dy++) {
				map[dx + 1][dy + 1] = (img.getRed(x + dx, y + dy) > 0)?1:0;
			}
		}
		
		return map;
	}
	@Override
	public int[][] follow() {
		int width = this.getImage().getWidth();
		int height = this.getImage().getHeight();
		Image img = this.getImage();
		
		int[][] bordermap = new int[width][height];
		
		ColorTransformer ct = new ColorTransformer();
		int[][][] ycc = ct.rgb2ycc(img);
		int[][] lum = ycc[0];
		
		int startx = 0, starty = 0;
		boolean done = false;
		for (int x = 0; x < width && !done; x++) {
			for (int y = 0; y < height && !done; y++) {
				int lumxy = lum[x][y]; 
				if (lumxy > 0) {
					startx = x;
					starty = y;
					bordermap[x][y] = 1;
					done = true;
				}
			}
		}
		
		int x = startx;
		int y = starty;
		
		int[] search_dir_x = { 0, 1, 0, -1};
		int[] search_dir_y = {-1, 0, 1,  0};
		int start_search_direction = 0;
		done = false;
		while (!done) {
			int search = start_search_direction;
			for (int i = 0; i < 4; i++, search = (search + 1)%4) {
				int dx = search_dir_x[search];
				int dy = search_dir_y[search];
				int red = img.getRed(x + dx, y + dy);
				if (red > 0) {
					x = x + dx;
					y = y + dy;
					bordermap[x][y] = 1;
					break;
				}
			}
			
			done = (x == startx && y == starty);
			start_search_direction = (search + 3) % 4;
		}

		return bordermap;
	}

}
